package com.mygame.components

import com.almasb.fxgl.entity.component.Component
import javafx.scene.input.KeyCode


class ComboComponent : Component() {
    private var lastInputTime: Long = 0L
    private var lastInputKey: String? = null
    private val inputKeys: MutableList<String> = mutableListOf()
    private val combos: MutableMap<MutableList<String>, Runnable> = HashMap()

    private var lastInputTimeMap: MutableMap<String, Long> = mutableMapOf()

    init {
        combos[arrayListOf(KeyCode.LEFT.name, KeyCode.DOWN.name, KeyCode.RIGHT.name)] = Runnable {
            println("←↓→ GO")
        }
        combos[arrayListOf(KeyCode.LEFT.name, KeyCode.RIGHT.name, KeyCode.LEFT.name)] = Runnable {
            println("←→← GO")
        }
    }

    override fun onAdded() {
        super.onAdded()
        lastInputTimeMap.set(KeyCode.UP.name, 0L)
        lastInputTimeMap.set(KeyCode.DOWN.name, 0L)
        lastInputTimeMap.set(KeyCode.LEFT.name, 0L)
        lastInputTimeMap.set(KeyCode.RIGHT.name, 0L)
    }

    fun addInputKeys(inputKey: String) {
        if (System.currentTimeMillis() - lastInputTime > 250) {//200毫秒内不搓招,清零连招
            inputKeys.clear()
            //println("清除:" + inputKeys)
            lastInputKey = inputKey
        }
        lastInputTime = System.currentTimeMillis()
        if (System.currentTimeMillis() - lastInputTimeMap.get(inputKey)!! < 250) {//
            return
        }
        lastInputTimeMap.put(inputKey, System.currentTimeMillis())
        if (inputKeys.isNotEmpty() && inputKeys.last().equals(inputKey)) {
            return
        }
        //println("lastInputKey:" + lastInputKey)
        lastInputKey = inputKey
        inputKeys.add(inputKey)

        if (inputKeys.size > 4) {
            var slist = inputKeys.subList(inputKeys.size - 3, inputKeys.size)
            //println("size>4截取:" + inputKeys.toString())
            if (combos.get(slist) != null) {
                combos.get(slist)?.run()
                inputKeys.clear()
            }
        } else {
            //println("size<5直接:" + inputKeys.toString())
            if (combos.get(inputKeys) != null) {
                combos.get(inputKeys)?.run()
                inputKeys.clear()
            }
        }
    }
}
